import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { config } from '../../shared/smartadmin.config'
import { Router, ActivatedRoute } from '@angular/router' //路由引入
declare var $: any
declare var Viewer: any
@Component({
  selector: 'sa-order',
  templateUrl: './Invoice.component.html',
  styleUrls: ['./Invoice.component.css']
})
export class InvoiceComponent implements OnInit {
  InvoiceEditFromOption = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      headName: {
        validators: {
          notEmpty: {
            message: '请输入付款方'
          }
        }
      },
      payeeName: {
        validators: {
          notEmpty: {
            message: '请输入收款方'
          }
        }
      },
      money: {
        validators: {
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                let isValid = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value)
                if (isValid) {
                  return true
                } else {
                  return {
                    valid: false,
                    message: '请输入正整数'
                  }
                }
              } else {
                return {
                  valid: false,
                  message: '请输入金额'
                }
              }
            }.bind(this)
          }
        }
      },
      // payTime: {
      //   validators: {
      //     notEmpty: {
      //       message: '请选择时间'
      //     }
      //   }
      // },
      typeExpense: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择费用类型'
          }
        }
      },
      remark: {
        validators: {
          notEmpty: {
            message: '请输入备注'
          }
        }
      }
    }
  }
  RiseEditFromOption = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      headName: {
        validators: {
          notEmpty: {
            message: '请输入名称'
          }
        }
      },
      dutyParagraph: {
        validators: {
          notEmpty: {
            message: '请输入税号'
          }
        }
      }
    }
  }
  ReceivingTnfoFromOption = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      shippingName: {
        validators: {
          notEmpty: {
            message: '请输入收货人'
          }
        }
      },
      shippingPhone: {
        validators: {
          callback: {
            callback: function (value, validator, $field) {
              if (value) {
                let isValid1 = /([0-9]{3,4}-)?[0-9]{7,8}/.test(value)
                let isValid2 =
                  /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/.test(
                    value
                  )
                if (value.indexOf('-') != -1) {
                  if (isValid1) {
                    return true
                  } else {
                    return {
                      valid: false,
                      message: '请输入正确手机号码'
                    }
                  }
                } else {
                  if (isValid2) {
                    return true
                  } else {
                    return {
                      valid: false,
                      message: '请输入正确手机号码'
                    }
                  }
                }
              } else {
                return {
                  valid: false,
                  message: '请输入手机号码'
                }
              }
            }.bind(this)
          }
        }
      },
      address: {
        validators: {
          notEmpty: {
            message: '请输入邮寄地址'
          }
        }
      },
      provinceId: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择省'
          }
        }
      },
      cityId: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择市'
          }
        }
      },
      townId: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择区'
          }
        }
      }
    }
  }
  tableData: any[] = [] //table数据
  resultTableData: any[] = [] //客户端分页数据暂存
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  companyCarModule: any = {
    selectedCompanyName: '', //过滤条件:公司name
    selectedCompanyId: '' //过滤条件:公司Id
  }
  tableSearch: any = {
    startTime: '', //开始时间
    endTime: '', //结束时间
    searchKey: '', //搜索keyword
    typeExpense: '',
    state: '',
    invoiceType: '',
    system: '',
    dateType: ''
  }
  TabType: string = 'apply' //tab激活标识,默认设备离线页面
  imgList: any = [] // 图片路径
  isViewer: boolean = false //默认隐藏
  viewer: any = ''

  //开票
  InvoiceStatusFrom: any = {
    id: '',
    invoiceType: 0,
    state: 3,
    expressDeliveryNumber: '',
    userEmail: '',
    invoiceUrl: '',
    isSendCopy: ''
  }

  //开票 编辑
  InvoiceEditFrom: any = {
    id: '',
    headName: '',
    payeeName: '',
    money: '',
    payTime: '',
    typeExpense: '',
    remark: ''
  }
  //查看详情
  ViewDetailsFrom: any = {
    headName: '',
    dutyParagraph: '',
    companyAddress: '',
    companyPhone: '',
    bankName: '',
    bankAccount: ''
  }

  //抬头管理
  RiseEditFrom: any = {
    id: '',
    headName: '',
    dutyParagraph: '',
    companyAddress: '',
    companyPhone: '',
    bankName: '',
    bankAccount: ''
  }

  //收货信息
  ReceivingTnfoFrom: any = {
    id: '',
    shippingName: '',
    shippingPhone: '',
    address: ''
  }

  allChecked: boolean = false //table全选状态值
  selected: any[] = [] //row选择的数据
  rowIds: string = '' //批量开票id
  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {
      this.curPage = queryParams.nowPage || 1
    })
  }
  // 接收子组件传递过来的数据
  getSelectTableTime(time) {
    this.tableSearch.startTime = time.startTime
    this.tableSearch.endTime = time.endTime
  }
  ngOnInit() {
    this.load()
    this.initDate()
    this.initdata()
  }
  //Tab 切换
  tabChange(type) {
    this.TabType = type
    this.curPage = 1
    this.pageSize = 10
    this.resultTableData = []
    this.tableSearch.searchKey = ''
    this.selected = []
    this.rowIds = ''
    this.allChecked = false
    this.load()
  }

  //table 全部选中
  allSelected() {
    this.allChecked = !this.allChecked
    if (!this.allChecked) {
      for (let item of this.resultTableData) {
        item['isChecked'] = false
      }
      this.selected = []
      this.rowIds = ''
    } else {
      var temArr = []
      for (let item of this.resultTableData) {
        item['isChecked'] = true
        temArr.push(item.id)
        this.selected.push(item)
      }
      for (let item of this.selected) {
        temArr.push(item.id)
      }
      this.rowIds = temArr.join(',')
    }
  }
  //table复选框数据row选中事件回调:处理选中状态和deviceId
  rowSelected(row, e, index) {
    var index = $.inArray(row, this.selected)
    if (index === -1) {
      row.isChecked = true
      this.selected.push(row)
    } else {
      row.isChecked = false
      this.selected.splice(index, 1)
    }
    var temArr = []
    for (let item of this.selected) {
      temArr.push(item.id)
    }
    this.rowIds = temArr.join(',') //处理deviceId,与后台接口交互参数
    this.selected.length === this.pageSize ? (this.allChecked = true) : (this.allChecked = false) //判断是否全选状态
  }
  // 批量开票
  invoiceStutas: number | string = '' //默认开票中
  batchInvoice(modal) {
    if (this.selected.length && this.rowIds != '') {
      this.invoiceStutas = ''
      // this.jsonApiService.confirm_message('确定已勾选数据批量开票?').then(() => {
      modal.show()

      // })
    } else {
      this.jsonApiService.message('请选中最少一条数据')
    }
  }
  //关闭批量开票弹窗
  batchInvoiceCloase(modal) {
    modal.hide()
  }
  //开启批量开票弹窗
  batchInvoiceSubmit(modal) {
    if (this.invoiceStutas == 1 || this.invoiceStutas == 3) {
      let reqdata = 'ids=' + this.rowIds + '&state=' + this.invoiceStutas
      this.jsonApiService.http('invoice/invoicingBatch.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        modal.hide()
        this.load()
      })
    } else {
      this.jsonApiService.message('请选择开票状态')
      return
    }
  }

  //初始化加载list数据
  load() {
    let data: any, Url: string
    let timeCheck = common.correctTimeParams(this.tableSearch.startTime, this.tableSearch.endTime, 0)
    const factoryId = this.tableSearch.factoryId || undefined
    if (!timeCheck.status) {
      this.jsonApiService.message(timeCheck.message)
      return
    }
    if (this.TabType == 'apply') {
      Url = 'invoice/invoiceData.html'
      data = {
        pageSize: this.pageSize,
        nowPage: this.curPage,
        parameters: {
          searchKey: this.tableSearch.searchKey.trim(),
          // companyId:this.companyCarModule.selectedCompanyId,
          startTime: this.tableSearch.startTime,
          endTime: this.tableSearch.endTime,
          typeExpense: this.tableSearch.typeExpense,
          state: this.tableSearch.state,
          invoiceType: this.tableSearch.invoiceType,
          system: this.tableSearch.system,
          dateType: this.tableSearch.dateType,
          export: '0', //是否导出
          factoryId
        }
      }
    } else if (this.TabType == 'rise') {
      Url = 'invoiceHead/invoiceHeadData.html'
      data = {
        pageSize: this.pageSize,
        nowPage: this.curPage,
        parameters: {
          searchKey: this.tableSearch.searchKey.trim(),
          export: '0', //是否导出
          factoryId
        }
      }
    } else if (this.TabType == 'address') {
      Url = 'shippingAddress/shippingAddressData.html'
      data = {
        pageSize: this.pageSize,
        nowPage: this.curPage,
        parameters: {
          searchKey: this.tableSearch.searchKey.trim(),
          export: '0', //是否导出
          factoryId
        }
      }
    }

    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http(Url, reqdata).subscribe(result => {
      if (!result.isSuccess) {
        this.jsonApiService.message(result.message)
        return
      }
      if (this.TabType == 'apply') {
        for (var i = 0; i < result.exhibitDatas.length; i++) {
          if (
            result.exhibitDatas[i].money != null &&
            result.exhibitDatas[i].money != '' &&
            result.exhibitDatas[i].money != 0
          ) {
            result.exhibitDatas[i].money = result.exhibitDatas[i].money / 100
          }
          // if (result.exhibitDatas[i].payTime.indexOf(':') != -1) {
          //   result.exhibitDatas[i].payTime = /\d{4}-\d{1,2}-\d{1,2}/g.exec(result.exhibitDatas[i].payTime)
          // }
        }
      }
      this.selected = []
      this.rowIds = ''
      this.allChecked = false
      this.resultTableData = result.exhibitDatas
      this.totalCount = result.recordCount
      // this.client_pages(0,this.pageSize);
    })
  }
  //导出
  dataExceport() {
    var data: any, Url: string
    if (this.TabType == 'apply') {
      Url = 'invoice/invoiceData.html'
      data = {
        pageSize: this.pageSize,
        nowPage: this.curPage,
        parameters: {
          searchKey: this.tableSearch.searchKey.trim(),
          factoryId: this.tableSearch.factoryId,
          startTime: this.tableSearch.startTime,
          endTime: this.tableSearch.endTime,
          typeExpense: this.tableSearch.typeExpense,
          state: this.tableSearch.state,
          invoiceType: this.tableSearch.invoiceType,
          system: this.tableSearch.system,
          dateType: this.tableSearch.dateType,
          export: '1' //是否导出
        }
      }
    } else if (this.TabType == 'rise') {
      Url = 'invoiceHead/invoiceHeadData.html'
      data = {
        pageSize: this.pageSize,
        nowPage: this.curPage,
        parameters: {
          searchKey: this.tableSearch.searchKey.trim(),
          export: '1' //是否导出
        }
      }
    } else if (this.TabType == 'address') {
      Url = 'shippingAddress/shippingAddressData.html'
      data = {
        pageSize: this.pageSize,
        nowPage: this.curPage,
        parameters: {
          searchKey: this.tableSearch.searchKey.trim(),
          export: '1' //是否导出
        }
      }
    }
    common.exprotDataFile(data, 'gridPager', config.BaseURL + Url)
  }
  ngOnDestroy() {
    document.onclick = null
  }
  //刷新
  refresh() {
    this.load()
  }
  //查询
  table_search() {
    this.curPage = 1
    this.resultTableData = []
    this.selected = []
    this.rowIds = ''
    this.allChecked = false
    this.load()
  }
  //前端分页
  client_pages(start, length) {
    this.resultTableData = this.tableData.slice(start, start + length)
  }
  //分页回调
  paginate(e) {
    this.resultTableData = []
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.selected = []
    this.rowIds = ''
    this.allChecked = false
    this.load()
    // this.client_pages(e.first,e.rows);
  }
  //公司选中回调[设备离线]
  companySelected(data) {
    this.companyCarModule.selectedCompanyId = data.companyId
    this.companyCarModule.selectedCompanyName = data.companyName
  }

  //开票申请
  //初始化日期
  initDate() {
    var that = this
    var dateTime = new Date().toLocaleDateString()
    System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
      System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
        $('#workPayTime')
          .datetimepicker({
            //时间插件
            format: 'yyyy-mm-dd',
            language: 'zh-CN',
            autoclose: true,
            minView: 2
          })
          .on('changeDate', function (e) {
            var date = e.date
            if (!date) {
              return
            }
            var time = common.getTimeDay(date)
            that.InvoiceEditFrom.payTime = time
          })
        $('#workPayTime').datetimepicker('setEndDate', dateTime)
      })
    })
  }

  //开票申请 删除
  deleteApplyBtn(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService.http('invoice/deletedById.html', 'id=' + row.id).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.TabType = 'apply'
          this.load()
        }
      })
    })
  }

  /**
   * 取消开票部分
   */
  CancelInvoiceStatusFrom = {
    id: '',
    cancelReason: ''
  }

  // 点击取消开票
  InvoiceCancelBtn(row, modal) {
    this.CancelInvoiceStatusFrom.id = row.id
    this.CancelInvoiceStatusFrom.cancelReason = ''
    modal.show()
  }

  // 提交取消开票
  CancelInvoiceStatusSubmit(modal) {
    const { id, cancelReason } = this.CancelInvoiceStatusFrom
    this.jsonApiService
      .http('invoice/cancelById.html', 'id=' + id + '&cancelReason=' + cancelReason)
      .subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.TabType = 'apply'
          this.load()
          modal.hide()
        }
      })
  }
  //取消开票 关闭
  CancelInvoiceStatusClose(modal) {
    this.InvoiceStatusFrom.id = ''
    this.InvoiceStatusFrom.state = 3
    this.InvoiceStatusFrom.expressDeliveryNumber = ''
    this.InvoiceStatusFrom.userEmail = ''
    modal.hide()
  }

  //开票申请 开票 弹出
  InvoiceStatusBtn(row, modal) {
    for (let key in this.InvoiceStatusFrom) {
      this.InvoiceStatusFrom[key] = row[key]
    }
    if (this.InvoiceStatusFrom.state == 0) {
      this.InvoiceStatusFrom.state = 3
    }
    modal.show()
  }

  //上传文件
  fileChange(files: FileList) {
    const multfileList = files
    const reqdata = new FormData()
    reqdata.append('describe', 'other')
    reqdata.append('businessType', '8')
    reqdata.append('type', '2') //type 1获取相对路径  2获取绝对路径
    const fileTemp = multfileList[0]
      const isJPG =
        fileTemp.type === 'application/pdf'
      const isLt4M = fileTemp.size / 1024 < 1024 * 10
      if (!isJPG) {
        this.jsonApiService.message('仅支持.pdf格式的文件!')
        return
      }
      if (!isLt4M) {
        this.jsonApiService.message('上传图片大小不能超过10M!')
        return
      }
      reqdata.append('files', fileTemp)
    this.jsonApiService.form_http('fileUpload/upload.html', reqdata).subscribe(data => {
      if (data.success) {
        console.log(data)
        this.InvoiceStatusFrom.invoiceUrl = data.data[0]
        // for (var i = 0; i < data.data.length; i++) {
        //   this.imageInfo.imageList.push(data.data[i])
        // }
      }
    })
    for (let k = 0; k < $('.up').length; k++) {
      $('.up')[k].value = null
    }
  }

  deleteFile(){
    this.InvoiceStatusFrom.invoiceUrl = ''
  }

  isNotice(val) {
		if (val) {
      this.InvoiceStatusFrom.isSendCopy = 1
		} else {
			this.InvoiceStatusFrom.isSendCopy = 0
		}
	}

  //开票申请 开票 确认
  InvoiceStatusSubmit(modal) {
    for (let key in this.InvoiceStatusFrom) {
      if (this.InvoiceStatusFrom[key] == null || this.InvoiceStatusFrom[key] == undefined) {
        this.InvoiceStatusFrom[key] = ''
      }
    }
    if (!this.InvoiceStatusFrom.state) {
      this.jsonApiService.message('请先选择开票状态')
      return
    }
    let reqdata = JSON.parse(JSON.stringify(this.InvoiceStatusFrom))
    reqdata.repairInfo = JSON.stringify(reqdata.repairInfo)
    this.jsonApiService.http_obj('invoice/makeOutInvoice.html', reqdata).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.TabType = 'apply'
        this.load()
        modal.hide()
      }
    })
  }
  //开票申请 开票 关闭
  InvoiceStatusClose(modal) {
    this.InvoiceStatusFrom.id = ''
    this.InvoiceStatusFrom.state = 3
    this.InvoiceStatusFrom.expressDeliveryNumber = ''
    this.InvoiceStatusFrom.userEmail = ''
    this.InvoiceStatusFrom.invoiceUrl = ''
    this.InvoiceStatusFrom.isSendCopy = ''
    modal.hide()
  }
  //开票申请 开票 选择
  clickSalesType(type) {
    this.InvoiceStatusFrom.state = type
  }

  //开票申请 编辑 弹出
  InvoiceEditBtn(row, modal) {
    for (let key in row) {
      this.InvoiceEditFrom[key] = row[key]
    }
    // if (row.payTime.indexOf(':') != -1) {
    //   row.payTime = /\d{4}-\d{1,2}-\d{1,2}/g.exec(row.payTime)
    // }

    $('#InvoiceEditFrom').data('bootstrapValidator').resetForm()
    modal.show()
  }
  // 选择费用类型
  typeChange(value) {
    this.InvoiceEditFrom.typeExpense = value
    $('#InvoiceEditFrom').data('bootstrapValidator').resetForm()
  }
  //开票申请 编辑 确认
  InvoiceEditSubmit(modal) {
    $('#InvoiceEditFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#InvoiceEditFrom').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      this.InvoiceEditFrom.money = this.InvoiceEditFrom.money * 100
      for (let key in this.InvoiceEditFrom) {
        if (this.InvoiceEditFrom[key] == null || this.InvoiceEditFrom[key] == undefined) {
          this.InvoiceEditFrom[key] = ''
        }
      }
      let reqdata = JSON.parse(JSON.stringify(this.InvoiceEditFrom))
      reqdata.repairInfo = JSON.stringify(reqdata.repairInfo)
      this.jsonApiService.http_obj('invoice/update.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.TabType = 'apply'
          this.load()
          modal.hide()
        }
      })
    }
  }
  //开票申请 编辑 关闭
  InvoiceEditClose(modal) {
    modal.hide()
  }

  //开票申请 查看详情 弹出
  ViewDetailsBtn(row, modal) {
    for (let key in row) {
      this.ViewDetailsFrom[key] = row[key]
    }
    modal.show()
  }
  //开票申请 查看详情 关闭
  ViewDetailsClose(modal) {
    modal.hide()
  }

  downloadInvoice(row) {
    if (row.invoiceFileURL !== '') {
      window.open(row.invoiceFileURL)
    }
  }

  //抬头管理
  //抬头管理 删除
  deleteRiseBtn(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService.http('invoiceHead/deletedById.html', 'id=' + row.id).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.TabType = 'rise'
          this.load()
        }
      })
    })
  }
  //抬头管理 编辑 弹出
  RiseEditBtn(row, modal) {
    for (let key in row) {
      this.RiseEditFrom[key] = row[key]
    }
    $('#RiseEditFrom').data('bootstrapValidator').resetForm()
    modal.show()
  }
  //抬头管理 编辑 关闭
  RiseEditClose(modal) {
    modal.hide()
  }
  //抬头管理 编辑 确认
  RiseEditSubmit(modal) {
    $('#RiseEditFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#RiseEditFrom').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      for (let key in this.RiseEditFrom) {
        if (this.RiseEditFrom[key] == null || this.RiseEditFrom[key] == undefined) {
          this.RiseEditFrom[key] = ''
        }
      }
      let reqdata = JSON.parse(JSON.stringify(this.RiseEditFrom))
      reqdata.repairInfo = JSON.stringify(reqdata.repairInfo)
      this.jsonApiService.http_obj('invoiceHead/update.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.TabType = 'rise'
          this.load()
          modal.hide()
        }
      })
    }
  }

  //地址管理
  //地址管理 删除
  deleteAddressBtn(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService.http('shippingAddress/deletedById.html', 'id=' + row.id).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.TabType = 'address'
          this.load()
        }
      })
    })
  }
  //地址管理 收货信息 弹出
  ReceivingTnfoBtn(row, modal) {
    for (let key in row) {
      this.ReceivingTnfoFrom[key] = row[key]
    }
    var temCity = row.address
    if (temCity) {
      this.provinceChange(this.ReceivingTnfoFrom.provinceId == null ? '' : this.ReceivingTnfoFrom.provinceId)
      this.cityChange(this.ReceivingTnfoFrom.cityId == null ? '' : this.ReceivingTnfoFrom.cityId)
      this.townChange(this.ReceivingTnfoFrom.townId == null ? '' : this.ReceivingTnfoFrom.townId)
    }
    $('#ReceivingTnfoFrom').data('bootstrapValidator').resetForm()
    modal.show()
  }
  //地址管理 收货信息 关闭
  ReceivingTnfoClose(modal) {
    modal.hide()
  }
  //地址管理 收货信息 确认
  ReceivingTnfoSubmit(modal) {
    $('#ReceivingTnfoFrom').bootstrapValidator('validate') //开启验证
    let isValid = $('#ReceivingTnfoFrom').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      for (let key in this.ReceivingTnfoFrom) {
        if (this.ReceivingTnfoFrom[key] == null || this.ReceivingTnfoFrom[key] == undefined) {
          this.ReceivingTnfoFrom[key] = ''
        }
      }
      delete this.ReceivingTnfoFrom['cityName']
      delete this.ReceivingTnfoFrom['provinceName']
      delete this.ReceivingTnfoFrom['townName']
      let reqdata = JSON.parse(JSON.stringify(this.ReceivingTnfoFrom))
      reqdata.repairInfo = JSON.stringify(reqdata.repairInfo)
      this.jsonApiService.http_obj('shippingAddress/update.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.TabType = 'address'
          this.load()
          modal.hide()
        }
      })
    }
  }

  areaData: any[] = [] //省市县数据
  provinceNameArr: any[] = [] //省数据
  cityNameArr: any[] = [] //城市数据
  townNameArr: any[] = [] //县数据
  //拉取省市县数据
  initdata() {
    this.jsonApiService.http('company/regionList.html', null).subscribe(data => {
      if (data.message) {
        this.areaData = data.data
        for (let item of this.areaData) {
          if (item.level === 2) {
            this.provinceNameArr.push(item)
          }
        }
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }
  //省份change回调事件
  provinceChange(e) {
    this.cityNameArr = []
    this.townNameArr = []
    this.ReceivingTnfoFrom.provinceId = e
    for (let item of this.areaData) {
      if (this.ReceivingTnfoFrom.provinceId === item.parentId) {
        this.cityNameArr.push(item)
      }
    }
    $('#ReceivingTnfoFrom').data('bootstrapValidator').resetForm()
  }
  //城市change回调事件
  cityChange(e) {
    this.townNameArr = []
    this.ReceivingTnfoFrom.cityId = e
    for (let item of this.areaData) {
      if (this.ReceivingTnfoFrom.cityId === item.parentId) {
        this.townNameArr.push(item)
      }
    }
    $('#ReceivingTnfoFrom').data('bootstrapValidator').resetForm()
  }
  townChange(e) {
    this.ReceivingTnfoFrom.townId = e
    $('#ReceivingTnfoFrom').data('bootstrapValidator').resetForm()
  }

  //公司选中回调
  projectSelected(data) {
    this.tableSearch.factoryId = data.companyId
  }

  applyInvoices(id: string) {
    this.router.navigate(['/contract/Invoice/invoice-apply-page'], {
      queryParams: { id, type: id ? 'update' : 'new', nowPage: this.curPage }
    })
  }

  // 查看图片
  showImg(url, modal) {
    modal.show()
    this.imgList = url
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
  }
  closeImg(modal) {
    modal.hide()
  }
  bigimg() {
    if (this.isViewer && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showBigImg()
          })
        })
      })
    } else {
      this.showBigImg()
    }
  }
  showBigImg() {
    var that = this
    var imgList = $('.imagesInfo')[0]
    this.viewer = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    that.isViewer = true
  }
}
